<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">物料编号</label>
        <el-input v-model="query.materialCode" clearable placeholder="物料编号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">物料描述</label>
        <el-input v-model="query.materialDescription" clearable placeholder="物料描述" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">供应区域</label>
        <el-input v-model="query.supplyZone" clearable placeholder="供应区域" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">状态</label>
        <el-select v-model="query.status" style="width: 185px;" placeholder="请选择" @change="crud.toQuery">
          <el-option
            v-for="item in dict.semi_material_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <el-button
          slot="right"
          type="primary"
          size="mini"
          class="filter-item"
          icon="el-icon-download"
          :loading="btn.download"
          plain
          @click="downloadExcel"
        >下载模板</el-button>
        <el-upload
          ref="uploadRef"
          slot="right"
          class="filter-item"
          :headers="headers"
          :action="uploadUrl"
          :limit="1"
          :show-file-list="false"
          :http-request="customUpload"
        >
          <el-button
            type="success"
            size="mini"
            :loading="btn.upload"
            icon="el-icon-upload2"
            plain
            @click="handleUpload"
          >上传物料表</el-button>
        </el-upload>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
          <el-form-item label="物料编号" prop="materialCode">
            <el-input v-model="form.materialCode" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="物料描述" prop="materialDescription">
            <el-input v-model="form.materialDescription" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="设定数量" prop="configQty">
            <el-input v-model.number="form.configQty" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="换箱数量" prop="swapQty">
            <el-input v-model.number="form.swapQty" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="供应区域" prop="supplyZone">
            <el-input v-model="form.supplyZone" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" style="width: 250px;" placeholder="请选择">
              <el-option
                v-for="item in dict.semi_material_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="保质期天数" prop="shelfLifeDays">
            <el-input v-model.number="form.shelfLifeDays" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="是否超标" prop="isOverLimit">
            <el-input v-model.number="form.isOverLimit" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="临期天数" prop="nearExpiryDays">
            <el-input v-model.number="form.nearExpiryDays" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="单根重量(g)" prop="unitWeight">
            <el-input v-model.trim="form.unitWeight" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="接料挪箱频率" prop="boxMoveFrequency">
            <el-input v-model.number="form.boxMoveFrequency" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="重量误差浮动(g)" prop="weightErr">
            <el-input v-model.trim="form.weightErr" style="width: 250px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="materialCode" label="物料编号" />
        <el-table-column prop="materialDescription" label="物料描述" />
        <el-table-column prop="configQty" label="设定数量" />
        <el-table-column prop="swapQty" label="换箱数量" />
        <el-table-column prop="supplyZone" label="供应区域" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ dict.label.semi_material_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column prop="shelfLifeDays" label="保质期天数" />
        <el-table-column prop="isOverLimit" label="是否超标" />
        <el-table-column prop="nearExpiryDays" label="临期天数" />
        <el-table-column prop="unitWeight" label="单根重量(g)">
          <template slot-scope="scope">
            {{ scope.row.unitWeight.toFixed(3) }}
          </template>
        </el-table-column>
        <el-table-column prop="boxMoveFrequency" label="接料挪箱频率" />
        <el-table-column prop="weightErr" label="重量误差浮动(g)">
          <template slot-scope="scope">
            {{ scope.row.weightErr.toFixed(3) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import crudSemiMaterial from '@/api/jtWork/jtMaterial'
import { downloadFileAPI, uploadFileAPI } from '@/api/jtWork/jtMaterial'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = { id: null, materialCode: null, materialDescription: null, configQty: null, swapQty: null, supplyZone: null, status: null, shelfLifeDays: null, isOverLimit: null, nearExpiryDays: null, unitWeight: null, createTime: null, updateTime: null, createName: null, updateName: null, boxMoveFrequency: null, weightErr: null }
export default {
  name: 'JtMaterial',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['semi_material_status'],
  cruds() {
    return CRUD({ title: 'semiMaterial', url: 'semiApi/semiMaterial', idField: 'id', sort: 'id,desc', crudMethod: { ...crudSemiMaterial }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'semiMaterial:add', 'otherUser'],
        edit: ['admin', 'semiMaterial:edit', 'otherUser'],
        del: ['admin', 'semiMaterial:del', 'otherUser']
      },
      rules: {
        materialCode: [
          // { required: true, message: '请输入物料编号', trigger: 'blur' }
        ],
        materialDescription: [
          // { required: true, message: '请输入物料描述', trigger: 'blur' }
        ],
        configQty: [
          // { required: true, message: '请输入设定数量', trigger: 'blur' },
          { type: 'number', message: '设定数量必须为数字', trigger: 'blur' }
        ],
        swapQty: [
          // { required: true, message: '请输入换箱数量', trigger: 'blur' },
          { type: 'number', message: '换箱数量必须为数字', trigger: 'blur' }
        ],
        supplyZone: [
          // { required: true, message: '请输入供应区域', trigger: 'blur' },
          // { max: 50, message: '供应区域长度不能超过50个字符', trigger: 'blur' }
        ],
        status: [
          // { required: true, message: '请输入状态', trigger: 'blur' },
          // { max: 20, message: '状态长度不能超过20个字符', trigger: 'blur' }
        ],
        shelfLifeDays: [
          // { required: true, message: '请输入保质期天数', trigger: 'blur' },
          { type: 'number', message: '保质期天数必须为数字', trigger: 'blur' }
        ],
        isOverLimit: [
          // { required: true, message: '请输入是否超标', trigger: 'blur' }
        ],
        nearExpiryDays: [
          // { required: true, message: '请输入临期天数', trigger: 'blur' },
          { type: 'number', message: '临期天数必须为数字', trigger: 'blur' }
        ],
        unitWeight: [
          // { required: true, message: '请输入单根重量', trigger: 'blur' },
          // { type: 'number', message: '单根重量必须为数字', trigger: 'blur' }
          {
            validator: (rule, value, callback) => {
              // 正则表达式：匹配整数或小数（支持正数、负数，可根据需求调整）
              const reg = /^[-+]?(\d+(\.\d*)?|\.\d+)$/
              if (value === '' || value === null || value === undefined) {
                // 如果非必填，空值直接通过
                callback()
              } else if (!reg.test(value)) {
                callback(new Error('单根重量必须为数字（可含小数）'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        boxMoveFrequency: [
          // { required: true, message: '请输入接料挪箱频率', trigger: 'blur' },
          { type: 'number', message: '接料挪箱频率必须为数字', trigger: 'blur' }
        ],
        weightErr: [
          // { required: true, message: '请输入重量误差浮动', trigger: 'blur' },
          // { type: 'number', message: '重量误差浮动必须为数字', trigger: 'blur' }
          {
            validator: (rule, value, callback) => {
              const reg = /^[-+]?(\d+(\.\d*)?|\.\d+)$/
              if (value === '' || value === null || value === undefined) {
                callback()
              } else if (!reg.test(value)) {
                callback(new Error('重量误差浮动必须为数字（可含小数）'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      queryTypeOptions: [
        { key: 'materialCode', display_name: '物料编号' },
        { key: 'materialDescription', display_name: '物料描述' },
        { key: 'supplyZone', display_name: '供应区域' },
        { key: 'status', display_name: '状态' }
      ],
      btn: {
        upload: false,
        download: false
      },
      headers: {
        'Authorization': getToken(),
        'Content-Type': 'multipart/form-data'
      },
      uploadUrl: process.env.VUE_APP_BASE_API + 'semiApi/semiMaterial/importExcel'
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    async downloadExcel() {
      try {
        this.btn.download = true
        const res = await downloadFileAPI()
        if (res && res instanceof Blob) {
          this.downloadFile(res)
        } else {
          this.message.warning('文件下载失败，返回数据不是有效的文件内容')
        }
      } finally {
        this.btn.download = false
      }
    },
    // 解析excel文件
    downloadFile(obj) {
      const url = window.URL.createObjectURL(new Blob([obj]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const fileName = '物料维护信息模板.xlsx'
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    },
    async customUpload(file) {
      const formData = new FormData()
      formData.append('file', file.file)
      try {
        this.btn.upload = true
        const res = await uploadFileAPI(formData)
        if (res.result === 'OK') {
          switch (res.data.errorMessages.length) {
            case 0:
              this.$message.success('上传物料成功')
              break
            case 1:
              this.$message.warning('上传失败的物料编号为：' + res.data.errorList.join(',') + '。失败原因：' + res.data.errorMessages[0])
              break
            default:
              this.$message.warning('上传失败的物料编号为：' + res.data.errorList.join(',') + '。失败原因：' + res.data.errorMessages.join('或'))
              break
          }
        } else {
          this.$message.warning(res.data)
        }
      } finally {
        this.btn.upload = false
      }
    },
    handleUpload() {
      this.$refs.uploadRef.clearFiles() // 清除已选择的文件
      this.$refs.uploadRef.submit() // 重新提交上传
    }
  }
}
</script>

<style scoped>

</style>
